//
//  GPAudioManager.m
//  Keping
//
//  Created by admin on 2019/1/22.
//  Copyright © 2019年 柯平. All rights reserved.
//

#import "GPAudioManager.h"
#import <AVFoundation/AVFoundation.h>

@interface GPAudioManager ()

@property(nonatomic, strong) AVPlayer *player;

@end

@implementation GPAudioManager

static id _instance;

+ (instancetype)shareManger {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (void)endPlay {
    [self.player pause];
}

- (void)playWithURL:(NSURL *)URL {
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:URL];
    __weak typeof(self) weakSelf = self;
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current = CMTimeGetSeconds(time);
        float total = CMTimeGetSeconds(item.duration);
        if (current == total) {
            // 播放完了
            AVPlayerItem *item = [AVPlayerItem playerItemWithURL:URL];
            [weakSelf.player replaceCurrentItemWithPlayerItem:item];
            [weakSelf.player play];
        }
    }];
    [self.player replaceCurrentItemWithPlayerItem:item];
    [self.player play];
}

- (AVPlayer *)player {
    if (_player == nil) {
        _player = [AVPlayer playerWithPlayerItem:nil];
    }
    return _player;
}

@end
